package com.smart.community.region.config;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 区域模块缓存配置类
 * 
 * @author Wu.Liang
 * @since 2024-12-21
 */
@Configuration
public class RegionCacheConfig {

    /**
     * 创建支持Java 8日期时间类型的Jackson序列化器
     * 解决LocalDateTime序列化问题
     */
    private GenericJackson2JsonRedisSerializer createJacksonSerializer() {
        ObjectMapper objectMapper = new ObjectMapper();
        
        // 注册Java 8时间模块
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        
        // 配置LocalDateTime的序列化和反序列化格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
        
        objectMapper.registerModule(javaTimeModule);
        
        // 启用默认类型信息，用于反序列化
        objectMapper.activateDefaultTyping(
            LaissezFaireSubTypeValidator.instance,
            ObjectMapper.DefaultTyping.NON_FINAL,
            JsonTypeInfo.As.PROPERTY
        );
        
        return new GenericJackson2JsonRedisSerializer(objectMapper);
    }

    /**
     * 配置区域模块专用的Redis缓存管理器
     * 使用@Primary注解确保此Bean优先被使用
     */
    @Bean
    @Primary
    public CacheManager regionCacheManager(RedisConnectionFactory connectionFactory) {
        // 创建支持Java 8日期时间类型的序列化器
        GenericJackson2JsonRedisSerializer jsonSerializer = createJacksonSerializer();
        
        // 默认缓存配置
        RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1)) // 默认1小时过期
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer))
                .disableCachingNullValues(); // 不缓存null值

        // 为不同的缓存区域配置不同的过期时间
        Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
        
        // 区域详情缓存 - 2小时
        cacheConfigurations.put("region:detail", defaultConfig.entryTtl(Duration.ofHours(2)));
        
        // 区域编码缓存 - 2小时
        cacheConfigurations.put("region:by-code", defaultConfig.entryTtl(Duration.ofHours(2)));
        
        // 区域类型缓存 - 4小时
        cacheConfigurations.put("region:by-type", defaultConfig.entryTtl(Duration.ofHours(4)));
        
        // 子区域缓存 - 2小时
        cacheConfigurations.put("region:children", defaultConfig.entryTtl(Duration.ofHours(2)));
        
        // 区域路径缓存 - 4小时
        cacheConfigurations.put("region:path", defaultConfig.entryTtl(Duration.ofHours(4)));
        
        // 区域树缓存 - 1小时
        cacheConfigurations.put("region:tree", defaultConfig.entryTtl(Duration.ofHours(1)));
        
        // 完整区域树缓存 - 30分钟
        cacheConfigurations.put("region:tree:complete", defaultConfig.entryTtl(Duration.ofMinutes(30)));

        // Feign：区域及其所有子区域（含自身） - 长时间缓存（30天）
        cacheConfigurations.put("region:feign:children-all", defaultConfig.entryTtl(Duration.ofDays(30)));
        
        // 建筑类型相关缓存 - 长时间缓存（30天），因为基础建筑类型是固定不变的
        cacheConfigurations.put("building:type:division:list", defaultConfig.entryTtl(Duration.ofDays(30)));
        cacheConfigurations.put("building:type:by:division", defaultConfig.entryTtl(Duration.ofDays(30)));
        cacheConfigurations.put("building:type:by:ids", defaultConfig.entryTtl(Duration.ofDays(30)));
        cacheConfigurations.put("building:type:top:level", defaultConfig.entryTtl(Duration.ofDays(30)));
        cacheConfigurations.put("building:type:by:category:type", defaultConfig.entryTtl(Duration.ofDays(30)));
        cacheConfigurations.put("building:type:by:division:type", defaultConfig.entryTtl(Duration.ofDays(30)));
        cacheConfigurations.put("building:type:tree", defaultConfig.entryTtl(Duration.ofDays(30)));
        
        // 社区信息缓存 - 2小时
        cacheConfigurations.put("community:detail", defaultConfig.entryTtl(Duration.ofHours(2)));
        
        // 楼栋信息缓存 - 2小时
        cacheConfigurations.put("building:detail", defaultConfig.entryTtl(Duration.ofHours(2)));

        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(defaultConfig)
                .withInitialCacheConfigurations(cacheConfigurations)
                .build();
    }
} 